import React from 'react';
import { inject, observer } from 'mobx-react';
import { routerShape } from 'react-router';
import { WeaTableNew, WeaLogView } from 'comsMobx';

let WeaTable = WeaTableNew.WeaTable;
import {
  WeaTop,
  WeaTab,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaLocaleProvider,
} from 'ecCom';
import { Button, Modal } from 'antd';
import { toJS } from 'mobx';
import PageSpin from '../public/PageSpin';
import PageLoadingSpin from '../public/PageLoadingSpin';
import NoViewRightPage from '../public/NoViewRightPage';

const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;
const WeaLogViewComp = WeaLogView.Component;

const store = ['routing', 'emailMonitorStore', 'emailMonitorLogStore'];

import * as EmailUtil from '../util/EmailUtil';
import MonitorLog from './monitor/MonitorLog';
import EmailConstant from '../constants/EmailConstant';
import MenuWithLayout from './menu/MenuWithLayout';

/**
 * 邮件 - 邮件监控
 */
@inject(...store)
@observer
class EmailMonitor extends React.Component {
  static contextTypes = {
    router: routerShape,
  };

  constructor(props) {
    super(props);
    this.state = {
      showLog: false,
      targetId: '',
    };
  }
  componentDidMount() {
    const { emailMonitorStore } = this.props;
    const { doTableLoading } = emailMonitorStore;

    // 必须要保证表单在列表查询之前初始化，如下写法存在异步，不保证先后顺序
    // emailMonitorStore.initConditionDatas(); //初始化高级搜索区域
    // emailMonitorStore.doTableLoading(); //查询列表
    // 改为回调
    emailMonitorStore.initConditionDatas('', doTableLoading); // 初始化高级搜索区域
  }

  componentWillUnmount() {
    // 组件卸载时一般清理一些状态
    const { emailMonitorStore } = this.props;

    emailMonitorStore.setShowSearchAd(false);
    emailMonitorStore.clearFormFields();
  }

  setShowSearchAd = (bool) => {
    this.props.emailMonitorStore.setShowSearchAd(bool);
  };

  hideSearchAd = () => this.props.emailMonitorStore.setShowSearchAd(false);

  onSearch = () => {
    const {
      emailMonitorStore: { searchParamsAd, doTableLoading },
    } = this.props;
    doTableLoading(searchParamsAd);
  };

  onSearchChange = (v) => {
    this.props.emailMonitorStore.appendFormFields({ subject: v });
  };

  render() {
    const { emailMonitorStore } = this.props;
    const {
      viewRightInitCompleted,
      viewRight,
      isDeleteing,
      comsWeaTableStore,
      loading,
      form,
      conditioninfo,
      showSearchAd,
      logStore,
      logstatus,
    } = emailMonitorStore;
    const { logType, logSmallType } = toJS(logstatus);
    if (!viewRightInitCompleted) {
      return (
        <PageSpin
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_PageSpin@dw05sp`}
        />
      );
    } else if (!viewRight) {
      return (
        <NoViewRightPage
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_NoViewRightPage@pbxi29`}
        />
      );
    }

    return (
      <div className="wea-email-monitor">
        <WeaRightMenu
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaRightMenu@glsikt`}
          datas={this.getRightMenu()}
          onClick={this.onRightMenuClick}
        >
          <WeaTop
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTop@fryt1p`}
            title={getLabel(384307, '邮件监控')}
            loading={loading}
            icon={EmailConstant.icon}
            iconBgcolor={EmailConstant.iconBgColor}
            buttons={this.getTopButtons()}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick}
          >
            <MenuWithLayout
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_MenuWithLayout@i4mcn8`}
              location={this.props.location}
            >
              <div className="title">{getLabel(132194, '监控列表')}</div>
              <WeaTab
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaTab@xs4wb8`}
                buttonsAd={this.getTabButtonsAd()}
                searchType={['base', 'advanced']}
                searchsBaseValue={
                  form.isFormInit &&
                  form.getFormParams() &&
                  form.getFormParams().subject
                }
                setShowSearchAd={this.setShowSearchAd}
                showSearchAd={showSearchAd}
                hideSearchAd={this.hideSearchAd}
                searchsAd={EmailUtil.getSearchs(form, conditioninfo, () => {
                  emailMonitorStore.setShowSearchAd(false);
                  emailMonitorStore.doTableLoading();
                })}
                onSearch={this.onSearch}
                onSearchChange={this.onSearchChange}
              />
              <WeaTable
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaTable@tacnwi`}
                comsWeaTableStore={comsWeaTableStore}
                loading={loading}
                needScroll={true}
                hasOrder={true}
                onOperatesClick={this.onOperatesClick}
              />
            </MenuWithLayout>
          </WeaTop>
        </WeaRightMenu>

        <MonitorLog
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_MonitorLog@ervh6e`}
        />

        <PageLoadingSpin
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_PageLoadingSpin@fxxzki`}
          display={isDeleteing}
        />
        <WeaLogViewComp
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaLogViewComp@acx3nn`}
          visible={this.state.showLog}
          onCancel={this.logViewCancel}
          logStore={logStore}
          logType={logType}
          logSmallType={logSmallType}
          targetId={this.state.targetId}
        />
      </div>
    );
  }

  logViewCancel = () => this.setState({ showLog: false });

  // 右键菜单
  getRightMenu() {
    let btns = [];
    btns.push({
      key: 'log',
      icon: <i className="icon-coms-Print-log" />,
      content: getLabel(83, '日志'),
    });
    btns.push({
      key: 'search',
      icon: <i className="icon-coms-search" />,
      content: getLabel(197, '搜索'),
    });
    btns.push({
      key: 'ShowCustomColumns',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(382660, '显示定制列'),
    });
    // btns.push({ key: "collection", icon: <i className='icon-coms-Custom'/>, content: '收藏' });
    // btns.push({ key: "help", icon: <i className='icon-coms-Custom'/>, content: '帮助' });
    return btns;
  }

  // 右键菜单事件绑定
  onRightMenuClick = (key) => {
    const { emailMonitorStore } = this.props;
    if (key == 'search') {
      emailMonitorStore.doTableLoading();
      emailMonitorStore.setShowSearchAd(false);
    } else if (key == 'ShowCustomColumns') {
      const { comsWeaTableStore, sessionkey } = toJS(emailMonitorStore);
      comsWeaTableStore.setColSetVisible(sessionkey, true);
      comsWeaTableStore.tableColSet(sessionkey, true);
    } else if (key == 'log') {
      this.setState({ showLog: true });
    }
  };

  onTabSearch = () => {
    const { emailMonitorStore } = this.props;
    emailMonitorStore.setShowSearchAd(false);
    emailMonitorStore.doTableLoading();
  };
  onTabReset = () => {
    const { emailMonitorStore } = this.props;
    const { conditioninfo } = emailMonitorStore;
    emailMonitorStore.setCondition(conditioninfo);
  };

  onTabCancel = () => {
    const { emailMonitorStore } = this.props;
    emailMonitorStore.setShowSearchAd(false);
  };

  // 高级搜索底部按钮定义
  getTabButtonsAd = () => [
    <Button
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_Button@2t2tsj@search`}
      type="primary"
      onClick={this.onTabSearch}
    >
      {getLabel(197, '搜索')}
    </Button>,
    <Button
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_Button@r6l77i@reset`}
      type="ghost"
      onClick={this.onTabReset}
    >
      {getLabel(2022, '重置')}
    </Button>,
    <Button
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_Button@zftxk8@oncancel`}
      type="ghost"
      onClick={this.onTabCancel}
    >
      {getLabel(201, '取消')}
    </Button>,
  ];

  // 执行搜索方法（也可用于刷新table）
  executeSearch = () => {
    const { emailMonitorStore } = this.props;
    emailMonitorStore.setShowSearchAd(false);
    emailMonitorStore.doTableLoading();
  };

  // 获得table选中行的主键值数组。若没选中任何一条，返回空数组
  getTableSelectedValues = () => {
    const { emailMonitorStore } = this.props;
    const { comsWeaTableStore } = emailMonitorStore;
    let values = comsWeaTableStore.selectedRowKeys;
    return values;
  };

  // 表格单元格转义
  onOperatesClick = (record, index, operate, flag) => {
    if (flag == 0) {
      // 删除
      let mailId = record.id;
      this.deleteMailFromMonitor(this, mailId);
    }
  };

  // top中的按钮
  getTopButtons() {
    let values = this.getTableSelectedValues();
    return [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@nmzfg2@ondelete`}
        type="primary"
        disabled={!values.length}
        onClick={this.deleteMailFromMonitor}
      >
        {getLabel(32136, '批量删除')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@adado3@monitorlog`}
        type="primary"
        onClick={this.showMonitorLog}
      >
        {getLabel(24622, '监控日志')}
      </Button>,
    ];
  }

  // 删除邮件
  deleteMailFromMonitor = (obj, mailIds) => {
    if (!mailIds) {
      mailIds = this.getTableSelectedValues().slice();
    }
    const { emailMonitorStore } = this.props;

    let reloadTable = this.executeSearch;
    confirm({
      title: getLabel(131329, '信息确认'),
      content: getLabel(384306, '确定删除选定的邮件吗？'),
      okText: getLabel(826, '确定'),
      onOk() {
        emailMonitorStore.deleteMailFromMonitor(
          {
            mailIds,
          },
          reloadTable,
        );
      },
      onCancel() {},
    });
  };

  showMonitorLog = () => {
    const { emailMonitorLogStore } = this.props;
    emailMonitorLogStore.showMonitorLogDialog(true);
  };
}

export default WeaTools.tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@nen2b9`}
      msg={
        props.error
          ? props.error
          : getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)(EmailMonitor);
